package com.atguigu.exam;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 编写一个服务器和一个客户端
 1)服务器上保存了几个用户名和对应的密码;且能验证客户端发送过来的用户名和密码,是否和保存的某个用户名和对应的密码一致.
 2)客户端能连接到服务器，并把用户在键盘上输入的用户名和密码，发送到服务器上
 * @author xbd
 * @create 2021-05-31 19:06
 */
public class UserPasswordTest {
    public void startServer(){
        ServerSocket ss = null;
        Socket socket = null;
        BufferedReader br = null;
        OutputStream os = null;
        try {
            String name = "admin";
            String password = "123123";
            ss = new ServerSocket(8899);
            socket = ss.accept();
            InputStream is = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            String user = br.readLine();
            System.out.println(user);

            os = socket.getOutputStream();
            String[] users = user.split(",");
            for(String s : users){
                System.out.println(s);
            }
            if(users[0].equals(name) && users[1].equals(password)){
                os.write("登陆成功".getBytes());
                System.out.println("登陆成功");
            }else {
                os.write("登陆失败".getBytes());
                System.out.println("");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }


    public static void main(String[] args) {
        new UserPasswordTest().startServer();
    }
}
